#include "GapGenerator.h"
#include "GapStateMap.h"
#include "SgwGapProxy.h"
#include "Trace.h"

namespace tsc
{
namespace mgw
{

using namespace tsc::common;

GapGenerator* GapGenerator::_instance = 0;

/*******************************************************************************
 *
 * Constructor
 *
 ******************************************************************************/
GapGenerator::GapGenerator(GeneratorEnvironment& ge) :
	Generator(ge, GapStateMap::instance().initialState()),
	mpT709(0),
	mpT711(0),
	mMgwId(0),
	mSocketConnId(0)
{
    mpT709 = new Timer(
                SgwGapProxy::instance().getRequestHandler(),
                getMgwId(),
                GAP_TIMER_ID_T709,
                TIMER_TYPE_GAP);
    mpT711 = new Timer(
                SgwGapProxy::instance().getRequestHandler(),
                getMgwId(),
                GAP_TIMER_ID_T711,
                TIMER_TYPE_GAP);

    if(SgwGapProxy::instance().sendGapConnectionInd(*this))
    {
        startT709();
        changeState(GapStateMap::mpStateRegisterPend);
    }
    else
    {
        startT711();
    }
} // GapGenerator::GapGenerator

/*******************************************************************************
 *
 * Destructor
 *
 ******************************************************************************/
GapGenerator::~GapGenerator()
{

}

void
GapGenerator::init(GeneratorEnvironment& ge)
{
	if(!_instance)
	{
		_instance = new GapGenerator(ge);
	}
}

GapGenerator& GapGenerator::instance()
{
	if(!_instance)
	{
		TRACE_ERROR("GapGenerator not initialized");
	}
    return *_instance;
}

//===================================================================
bool
GapGenerator::txEnabled() const
{
    return static_cast<GapStateBase*>(_currentState)->txEnabled();
}

uint32_t
GapGenerator::getMgwId() const
{
    return mMgwId;
}

void
GapGenerator::setMgwId(const uint32_t id)
{
    mMgwId = id;
}

void
GapGenerator::startT709(unsigned long valueMs)
{
    mpT709->start(valueMs);
}

void
GapGenerator::cancelT709()
{
    mpT709->cancel();
}

void
GapGenerator::startT711(unsigned long valueMs)
{
    mpT711->start(valueMs);
}

void
GapGenerator::cancelT711()
{
    mpT711->cancel();
}

unsigned int
GapGenerator::getSocketConnectionId()
{
    return mSocketConnId;
}

} // namespace sgw
} // namespace tsc
